package test.udp.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

public class MultiServer {
	public static void main(String args[]) throws Exception {
		try {
			// 创建Socket
			MulticastSocket socket = new MulticastSocket(10000);
			InetAddress group = InetAddress.getByName("231.0.0.0");
			socket.joinGroup(group);
			
			// 接收数据包
			for (int i = 0; i < 100; i++) {
				byte[] buffer = new byte[256];
				DatagramPacket receivePackage = new DatagramPacket(buffer,
						buffer.length);
				socket.receive(receivePackage);

				byte[] buffer2 = new byte[receivePackage.getLength()];
				System.arraycopy(receivePackage.getData(), 0, buffer2, 0,
						receivePackage.getLength());
				System.out.println(new String(buffer2));
			}
			
			// 删除组播地址
			socket.leaveGroup(group);
			socket.close();

		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
